<template>
  <el-dialog
    v-model="visibleLocal"
    :title="mode === 'create' ? '添加成员' : '编辑成员'"
    width="520px"
    destroy-on-close
    @closed="handleClosed"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="用户ID" prop="user_id">
        <el-input v-model="form.user_id" placeholder="请输入用户ID" />
      </el-form-item>
      <el-form-item label="成员角色" prop="member_role">
        <el-select v-model="form.member_role" placeholder="请选择角色">
          <el-option
            v-for="item in MEMBER_ROLE_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="职位">
        <el-input v-model="form.position" placeholder="职位" />
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-switch
          v-model="form.status"
          :inactive-value="0"
          :active-value="1"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import memberApi, {
  MEMBER_ROLE_OPTIONS,
  type OrgMemberItem
} from "@/api/system/org/member";

const props = defineProps<{
  visible: boolean;
  organization: { id: number } | null;
  member: OrgMemberItem | null;
  mode: "create" | "edit";
}>();

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}>();

const formRef = ref();
const submitting = ref(false);
const visibleLocal = ref(props.visible);

const form = reactive({
  user_id: "",
  member_role: "member",
  position: "",
  status: 1
});

const rules = {
  user_id: [{ required: true, message: "请输入用户ID", trigger: "blur" }]
};

const assignForm = (member: OrgMemberItem | null) => {
  if (!member) {
    form.user_id = "";
    form.member_role = "member";
    form.position = "";
    form.status = 1;
    return;
  }
  form.user_id = String(member.user_id ?? "");
  form.member_role = member.member_role ?? "member";
  form.position = member.position ?? "";
  form.status = member.status ?? 1;
};

watch(
  () => props.visible,
  value => {
    visibleLocal.value = value;
  }
);

watch(
  () => props.member,
  value => {
    if (props.mode === "edit") {
      assignForm(value ?? null);
    }
  },
  { immediate: true }
);

const handleClose = () => {
  visibleLocal.value = false;
  emit("update:visible", false);
};

const handleClosed = () => {
  assignForm(props.mode === "edit" ? props.member ?? null : null);
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch {
    return;
  }

  if (!props.organization) {
    ElMessage.error("请先选择组织");
    return;
  }

  submitting.value = true;
  try {
    const payload = {
      org_id: props.organization.id,
      user_id: Number(form.user_id),
      member_role: form.member_role,
      position: form.position,
      status: form.status
    };

    if (props.mode === "edit" && props.member) {
      await memberApi.update(props.member.id, payload);
      ElMessage.success("成员已更新");
    } else {
      await memberApi.create(payload);
      ElMessage.success("成员已添加");
    }

    emit("success");
    handleClose();
  } catch (error: any) {
    ElMessage.error(error?.message ?? "保存成员失败");
  } finally {
    submitting.value = false;
  }
};
</script>
